package com.xhy.documents_collection.controller.admin;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.xhy.documents_collection.entity.VO.DarkRoomUser;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.entity.PO.log.SysLog;
import com.xhy.documents_collection.entity.PO.authority.Role;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.entity.PO.team.UserRole;
import com.xhy.documents_collection.restrict.Restrict;
import com.xhy.documents_collection.restrict.RestrictHandler;
import com.xhy.documents_collection.restrict.impl.CounterRestrict;
import com.xhy.documents_collection.service.authority.RoleService;
import com.xhy.documents_collection.service.authority.UserRoleService;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.utils.R;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author B站-xhyOVO
 * @since 2022-06-04
 * 用户
 */
@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleService roleService;



    @GetMapping("/list")
    @Authority("admin:user:list")
    public R list(){
        return R.ok().data("data",userService.list(new QueryWrapper<User>().select("id","name")));
    }
    /**
     * 用户列表
     * @param current
     * @param limit
     * @param name
     * @return
     */
    @GetMapping("/page")
    @Authority("admin:user:page")
    public R list(@RequestParam(value = "page",defaultValue = "1") Long current,
                  @RequestParam(value = "limit",defaultValue = "15") Long limit,
                  @RequestParam(required = false) String name,
                  @RequestParam(required = false) String studentNumber,
                  @RequestParam(required = false) String email
                  ){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        wrapper.like(!ObjectUtils.isEmpty(name),User::getName,name)
                .like(!ObjectUtils.isEmpty(studentNumber),User::getStudentNumber,studentNumber)
                .like(!ObjectUtils.isEmpty(email),User::getEmail,email);

        Page<User> page = userService.page(new Page<>(current, limit), wrapper);
        // 查出用户角色中间表
        Map<Integer, List<UserRole>> userRoleMap = userRoleService.list().stream().collect(Collectors.groupingBy(UserRole::getUId));
        // 根据角色查出角色表信息
        Map<Integer, String> roleMap = roleService.list().stream().collect(Collectors.toMap(Role::getId, Role::getName));
        Map<Integer, Set<String>> map = new HashMap();
        userRoleMap.forEach((uId,rIds)->{
            Set<String> roles = new HashSet<>();
            for (UserRole rId : rIds) {
                roles.add(roleMap.get(rId.getRId()));
            }
            map.put(uId,roles);
        });
        for (User user : page.getRecords()) {
            user.setRoleName(map.get(user.getId()));
        }
        return R.ok().data("data",page.getRecords()).count(page.getTotal());
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping
    @Authority("admin:user:add")
    public R add(@RequestBody @Validated User user){
        return userService.addUser(user);
    }

    @PutMapping
    @Authority("admin:user:update")
    public R update(@RequestBody @Validated User user){
        userService.updateById(user);
        return R.ok().message("修改成功");
    }


    @DeleteMapping("/{ids}")
    @Authority("admin:user:delete")
    public R delete(@PathVariable @NotBlank(message = "删除用户不可为空") String ids){
        return userService.removeUsers(ids);
    }


    @GetMapping("/darkRoom")
    @Authority("admin:darkRoom:user:list")
    public R getDarkRoomInUsers(){
        Set<DarkRoomUser> darkRoomUsers = CounterRestrict.listUsers();
        return R.ok().data("data", darkRoomUsers).count(darkRoomUsers.size());
    }

    @PostMapping("/darkRoom/relieve")
    @Authority("admin:darkRoom:user:relieve")
    public R relieveDarkRoomInUser(String key){
        CounterRestrict restrict = (CounterRestrict)RestrictHandler.getRestrict();
        restrict.removeDarkRoomInUser(key);
        return R.ok().message("解除成功");
    }

}

